package com.wms.token.buffer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.servlet.AsyncContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.wms.token.proxys.CheckIN;


public class Worker implements ServletContextListener{
	
	private static volatile BlockingQueue<AsyncContext> queue = new LinkedBlockingQueue<AsyncContext>();
	
	private static final Logger logger = Logger.getLogger(Worker.class);
	
	private volatile Thread thread;
	
	private static final int MAXBUFFERSIZE = 1000; //buffer临界值
	
    public static int add(AsyncContext c){
    	
      if(queue.size() > MAXBUFFERSIZE){
    	  return 0;
      }
      queue.add(c);
      logger.debug("****** Token Add ******");
      return 1;
    }
	
	private static CheckIN proxy;
	
	public static void setProxy(CheckIN proxy) {
		Worker.proxy = proxy;
	}


	@Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
	    
    	thread = new Thread(new Runnable(){
  		   @Override
  	       public void run() {
  			  AsyncContext context;
  	          while (true) {
	  	          try {
		  	           if(queue.size() == 0){
		  	        	   Thread.sleep(300);
		  	           }
	  	               while ((context = queue.poll()) != null) {
	  	            	   logger.debug("************** buffer of token, queue poll success, do run.  **************");
	  	                   try {
	  	                	 proxy.doRun((HttpServletRequest)context.getRequest(), (HttpServletResponse)context.getResponse());//调用Standard 类型 代理
	  	                   } catch (Exception e) {
	  	                	   		e.printStackTrace();
	  	                   } finally {
	  	                	   		context.complete();
	  	                   }
	  	               }
	  	          } catch (InterruptedException e) {
	  	            return;
	  	          }
  	          }
  	       }
  	    });
	    thread.start();
    }
    
    
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    	thread.interrupt();
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
